package com.chd.driversystem.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.anderson.dashboardview.view.DashboardView;
import com.chd.driversystem.R;
import com.chd.driversystem.activity.msgbean.NetMsg;
import com.chd.driversystem.domain.DrivingRecord;
import com.chd.driversystem.domain.Evaluation;
import com.chd.driversystem.domain.Oil;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.service.HttpService;
import com.chd.driversystem.util.network.tools.HttpConstants;
import com.chd.driversystem.util.tools.Constants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.MyApplication;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.charts.RadarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.data.RadarData;
import com.github.mikephil.charting.data.RadarDataSet;
import com.github.mikephil.charting.data.RadarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.interfaces.datasets.IRadarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class EvaluationActivity extends BaseActivity {
    public static final String TAG = "EvaluationActivity";

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.civ_avator)
    CircleImageView civAvator;

    @BindView(R.id.tv_username)
    TextView tvUserName;

    @BindView(R.id.tv_usercode)
    TextView tvUserCode;

    @BindView(R.id.tv_vehcode)
    TextView tvVehCode;

    @BindView(R.id.pc_tscoremaker)
    PieChart pcTscoreMaker;

    @BindView(R.id.rc_scorerader)
    RadarChart rcScoreRader;

    @BindView(R.id.lc_allscore)
    LineChart lcAllScore;

    @BindView(R.id.tv_tscore)
    TextView tvTscore;

    @BindView(R.id.tv_rapidacc)
    TextView tvRapidAcc;

    @BindView(R.id.tv_rapiddec)
    TextView getTvRapidDec;

    @BindView(R.id.tv_fuel)
    TextView tvFuel;

    @BindView(R.id.tv_distance)
    TextView tvDistance;

    private User user;
    private Evaluation evaluation;
    private int evaluaionType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluation);
        ButterKnife.bind(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        toolbar.setTitle("个人评测");
        toolbar.setContentInsetStartWithNavigation(430);
        setSupportActionBar(toolbar);

        Intent intent = getIntent();
        Long userId = intent.getLongExtra(Constants.EXTRA_PARAM1, -1);
        evaluaionType = intent.getIntExtra(Constants.EXTRA_PARAM2, -1);
        if (userId > 0) {
            user = BeanServer.getInstance().getUserById(userId);
            evaluation = BeanServer.getInstance().getLastEvaluationByType(user.getId(), evaluaionType);
        } else {
            Log.d(TAG, "onCreate() err: userId = " + userId);
            finish();
        }
        //后台服务参数
        params = new HashMap<>();
        params.put(Constants.EXTRA_PARAM1, userId);
        params.put(Constants.EXTRA_PARAM2, evaluaionType);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            // actionBar.setHomeAs
        }

        initView();

    }

    private void initView() {
        tvUserName.setText(user.getName());
        tvUserCode.setText("工号:" + user.getCode());
        if (evaluation!=null) {
            initRadarChart();
            initPieCharts();
            initLineCharts();
        }
    }

    private void initRadarChart() {

        tvTscore.setText(evaluation.getTScore()+"分");

        rcScoreRader.setBackgroundColor(Color.TRANSPARENT);

        rcScoreRader.getDescription().setEnabled(false);

        rcScoreRader.setWebLineWidth(1f);
        rcScoreRader.setWebColor(Color.LTGRAY);
        rcScoreRader.setWebLineWidthInner(1f);
        rcScoreRader.setWebColorInner(Color.LTGRAY);
        rcScoreRader.setWebAlpha(100);
        rcScoreRader.setRotationEnabled(false);

        // create a custom MarkerView (extend MarkerView) and specify the layout
        // to use for it
        rcScoreRader.animateXY(
                1400, 1400,
                Easing.EasingOption.EaseInOutQuad,
                Easing.EasingOption.EaseInOutQuad);

        XAxis xAxis = rcScoreRader.getXAxis();
        xAxis.setTextSize(10f);
        xAxis.setYOffset(0f);
        xAxis.setXOffset(0f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {

            private String[] mActivities = new String[]{"稳定性", "操作", "车辆健康", "驾驶经验", "经济驾驶"};

            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mActivities[(int) value % mActivities.length];
            }
        });
        xAxis.setTextColor(Color.BLACK);

        YAxis yAxis = rcScoreRader.getYAxis();
        yAxis.setLabelCount(5, false);
        yAxis.setTextSize(9f);
        yAxis.setAxisMinimum(0f);
        yAxis.setAxisMaximum(80f);
        yAxis.setDrawLabels(false);

        Legend l = rcScoreRader.getLegend();
        l.setEnabled(false);
        refreshRaderCharts();
    }

    private void refreshRaderCharts() {

        ArrayList<RadarEntry> entries = new ArrayList<RadarEntry>();

        entries.add(new RadarEntry(evaluation.getStability()));
        entries.add(new RadarEntry(evaluation.getOpSpec()));
        entries.add(new RadarEntry(evaluation.getVehHealth()));
        entries.add(new RadarEntry(evaluation.getDrExpericen()));
        entries.add(new RadarEntry(evaluation.getEsDriving()));

        RadarDataSet dataSet = new RadarDataSet(entries, "驾驶评测");
        dataSet.setColor(Color.rgb(103, 110, 129));
        dataSet.setFillColor(Color.rgb(103, 110, 129));
        dataSet.setDrawFilled(true);
        dataSet.setFillAlpha(180);
        dataSet.setLineWidth(2f);
        dataSet.setDrawHighlightCircleEnabled(true);
        dataSet.setDrawHighlightIndicators(false);


        RadarData data = new RadarData(dataSet);
        data.setValueTextSize(10f);
        data.setDrawValues(true);
        data.setValueTextColor(Color.BLACK);

        rcScoreRader.setData(data);

        rcScoreRader.invalidate();
    }

    private void initPieCharts() {
        /**************************饼图********************************/
        //饼图--优良比例
        pcTscoreMaker.setUsePercentValues(true);
        pcTscoreMaker.getDescription().setEnabled(false);
        pcTscoreMaker.setExtraOffsets(5, 10, 5, 5);

        pcTscoreMaker.setDragDecelerationFrictionCoef(0.95f);

        pcTscoreMaker.setCenterText("组成");

        pcTscoreMaker.setDrawHoleEnabled(true);
        pcTscoreMaker.setHoleColor(Color.WHITE);

        pcTscoreMaker.setTransparentCircleColor(Color.WHITE);
        pcTscoreMaker.setTransparentCircleAlpha(110);

        pcTscoreMaker.setHoleRadius(40f);
        pcTscoreMaker.setTransparentCircleRadius(43f);

        pcTscoreMaker.setDrawCenterText(true);

        pcTscoreMaker.setRotationAngle(270);
        // enable rotation of the chart by touch
        pcTscoreMaker.setRotationEnabled(true);
        pcTscoreMaker.setHighlightPerTapEnabled(true);

        // rcScoreRader.setUnit(" €");
        // rcScoreRader.setDrawUnitsInChart(true);

        // add a selection listener
        pcTscoreMaker.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {

            }

            @Override
            public void onNothingSelected() {

            }
        });

        pcTscoreMaker.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        // rcScoreRader.spin(2000, 0, 360);

        Legend l = pcTscoreMaker.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(20f);
        // entry label styling
        pcTscoreMaker.setEntryLabelColor(Color.TRANSPARENT);
        pcTscoreMaker.setEntryLabelTextSize(12f);
        refreshPieChart();
    }

    private void refreshPieChart() {
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        entries.add(new PieEntry(evaluation.getStability(), "稳定性"));
        entries.add(new PieEntry(evaluation.getEsDriving(), "经济性"));
        entries.add(new PieEntry(evaluation.getDrExpericen(), "经验"));
        entries.add(new PieEntry(evaluation.getOpSpec(), "操作"));
        entries.add(new PieEntry(evaluation.getVehHealth(), "车辆健康"));

        PieData data = pcTscoreMaker.getData();
        PieDataSet dataSet;
        if (data != null && data.getDataSetCount() > 0) {
            dataSet = (PieDataSet) data.getDataSet();
            dataSet.setValues(entries);
            data.notifyDataChanged();
            pcTscoreMaker.notifyDataSetChanged();
            pcTscoreMaker.invalidate();
        } else {
            dataSet = new PieDataSet(entries, "分数比例组成图");

            dataSet.setDrawIcons(false);

            dataSet.setSliceSpace(3f);
            dataSet.setIconsOffset(new MPPointF(0, 40));
            dataSet.setSelectionShift(5f);

            // add a lot of colors

            ArrayList<Integer> colors = new ArrayList<Integer>();

            for (int c : ColorTemplate.VORDIPLOM_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.JOYFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.COLORFUL_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.LIBERTY_COLORS)
                colors.add(c);

            for (int c : ColorTemplate.PASTEL_COLORS)
                colors.add(c);

            colors.add(ColorTemplate.getHoloBlue());

            dataSet.setColors(colors);
            //dataSet.setSelectionShift(0f);

            data = new PieData(dataSet);
            data.setValueFormatter(new PercentFormatter());
            data.setValueTextSize(11f);
            data.setValueTextColor(Color.BLACK);

            pcTscoreMaker.setData(data);
            pcTscoreMaker.highlightValues(null);
            pcTscoreMaker.invalidate();
        }
    }

    private void initLineCharts() {
//折线图--分数走势图
        lcAllScore.setPinchZoom(true);
        lcAllScore.setScaleYEnabled(false);
        lcAllScore.setLogEnabled(false);
        lcAllScore.setDrawGridBackground(true);
        lcAllScore.setGridBackgroundColor(Color.TRANSPARENT);
        lcAllScore.setDrawBorders(true);
        lcAllScore.setBorderColor(Color.WHITE);
        lcAllScore.setHighlightPerDragEnabled(true);
        lcAllScore.setHighlightPerTapEnabled(true);
        Description des = new Description();
        des.setText("驾驶能力各指标走势图");
        lcAllScore.setDescription(des);
        lcAllScore.animateX(2500);
        refreshLineCharts(evaluaionType);
    }

    private void refreshLineCharts(int type) {
        LogUtil.d(TAG, "refreshLineCharts() called with: type = [" + type + "]");
        List<Evaluation> evaluations = BeanServer.getInstance().getEvaluationsByType(user.getId(), type);
        List<Entry> tscore = new ArrayList<>();
//        List<Entry> stabilities = new ArrayList<>();
//        List<Entry> opSpeces = new ArrayList<>();
//        List<Entry> vehHealths = new ArrayList<>();
//        List<Entry> drExpericens = new ArrayList<>();
        List<Entry> esDriving = new ArrayList<>();
        if (evaluations.size() > 0) {
            long x = 0;
            for (Evaluation eva : evaluations) {
                x++;
                Log.d(TAG, "refreshLineCharts: x=" + eva.getCreateDate());
                tscore.add(new Entry(x, eva.getTScore()));
//                stabilities.add(new Entry(x, eva.getStability()));
//                opSpeces.add(new Entry(x, eva.getOpSpec()));
//                vehHealths.add(new Entry(x, eva.getVehHealth()));
//                drExpericens.add(new Entry(x, eva.getDrExpericen()));
                esDriving.add(new Entry(x, eva.getEsDriving()));
            }
            LineData lineData = lcAllScore.getData();
            LineDataSet dsTscore;
            LineDataSet dsStabilities;
            LineDataSet dsOpSpeces;
            LineDataSet dsVehHealths;
            LineDataSet dsDrExpericens;
            LineDataSet dsEsDriving;
            if (lineData != null &&
                    lineData.getDataSetCount() > 0) {
                dsTscore = (LineDataSet) lineData.getDataSetByIndex(0);
                dsTscore.setValues(tscore);

//                dsStabilities = (LineDataSet) lineData.getDataSetByIndex(1);
//                dsStabilities.setValues(stabilities);
//
//                dsOpSpeces = (LineDataSet) lineData.getDataSetByIndex(2);
//                dsOpSpeces.setValues(opSpeces);
//
//                dsVehHealths = (LineDataSet) lineData.getDataSetByIndex(3);
//                dsVehHealths.setValues(vehHealths);
//
//                dsDrExpericens = (LineDataSet) lineData.getDataSetByIndex(4);
//                dsDrExpericens.setValues(drExpericens);

                dsEsDriving = (LineDataSet) lineData.getDataSetByIndex(1);
                dsEsDriving.setValues(esDriving);

                lineData.notifyDataChanged();
                lcAllScore.notifyDataSetChanged();
                lcAllScore.invalidate();
            } else {
                dsTscore = new LineDataSet(tscore, "综合");
                dsTscore.setColor(Color.GREEN);
                dsTscore.setValueTextColor(Color.rgb(73, 255, 0));
                dsTscore.setDrawCircles(false);
                dsTscore.setCubicIntensity(0.6f);
                dsTscore.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

//                dsStabilities = new LineDataSet(stabilities, "稳定性");
//                dsStabilities.setColor(Color.MAGENTA);
//                dsStabilities.setValueTextColor(Color.rgb(73, 255, 0));
//                dsStabilities.setDrawCircles(false);
//                dsStabilities.setCubicIntensity(0.6f);
//                dsStabilities.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//
//                dsOpSpeces = new LineDataSet(opSpeces, "操作");
//                dsOpSpeces.setColor(Color.YELLOW);
//                dsOpSpeces.setValueTextColor(Color.rgb(73, 255, 0));
//                dsOpSpeces.setDrawCircles(false);
//                dsOpSpeces.setCubicIntensity(0.6f);
//                dsOpSpeces.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//
//                dsVehHealths = new LineDataSet(vehHealths, "车辆健康");
//                dsVehHealths.setColor(Color.GRAY);
//                dsVehHealths.setValueTextColor(Color.rgb(73, 255, 0));
//                dsVehHealths.setDrawCircles(false);
//                dsVehHealths.setCubicIntensity(0.6f);
//                dsVehHealths.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
//
//                dsDrExpericens = new LineDataSet(drExpericens, "驾驶经验");
//                dsDrExpericens.setColor(Color.CYAN);
//                dsDrExpericens.setValueTextColor(Color.rgb(73, 255, 0));
//                dsDrExpericens.setDrawCircles(false);
//                dsDrExpericens.setCubicIntensity(0.6f);
//                dsDrExpericens.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

                dsEsDriving = new LineDataSet(esDriving, "经济驾驶");
                dsEsDriving.setColor(Color.BLUE);
                dsEsDriving.setValueTextColor(Color.rgb(73, 255, 0));
                dsEsDriving.setDrawCircles(false);
                dsEsDriving.setCubicIntensity(0.6f);
                dsEsDriving.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

                List<ILineDataSet> dataSets = new ArrayList<>();
                dataSets.add(dsTscore);
                dataSets.add(dsEsDriving);

                lineData = new LineData(dataSets);
                lcAllScore.setData(lineData);
                lcAllScore.invalidate();
            }

        }
    }


    public static void actionStart(Context context, Long userId, Integer type) {
        Intent intent = new Intent(context, EvaluationActivity.class);
        intent.putExtra(Constants.EXTRA_PARAM1, userId);
        intent.putExtra(Constants.EXTRA_PARAM2, type);
        context.startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_driver:

                break;
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void receiverNetMsg(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.BACKGROUND) {
            LogUtil.d(TAG, "receiverNetMsg() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATION:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getCount() > 0) {
                            LogUtil.d(TAG, "onReceive() count = " + netMsg.getCount());
                            refreshLineCharts(evaluaionType);
                            netMsg.setType(NetMsg.MAIN);
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
